'use strict';
const templateids = [
	'qXqSz5dTr6S67VmfIz_o4R0FkNZnwM1kp5a6Q4XOGbQ',
	'wSGuPQRBsw8GJYVm7wttEtfuZFEGrs7xolyNIaFnWZs',
	'vY_9n--pLwOn3Dfj0FdG1SB5c5UYfHLRV_sSaquk2fA'
]
const { POINT_CONVERSION_COMPRESSED } = require('constants');
const UniSubscribemsg = require('uni-subscribemsg');

function truncate(str){
	return str.substr(0,Math.min(str.length,20))
}

function getNotifyData(req) {
	if (req.index === 0) {
		return {
			thing2: {
				value: truncate(req.channel)
			},
			thing4: {
				value: truncate(req.parts)
			},
			amount3: {
				value: req.amount
			},
			time1: {
				value: req.time
			}
		}
	}
	if (req.index === 1) {
		return {
			thing1: {
				value: truncate(req.channel)
			},
			thing4: {
				value: truncate(req.parts)
			},
			thing3: {
				value: req.amount
			},
			date2: {
				value: req.time
			}
		}
	}
	return {
		character_string1: {
			value: req.sn
		},
		thing2: {
			value: truncate(req.parts)
		}
	}
}
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	const dbJQL = uniCloud.databaseForJQL({ // 获取JQL database引用，此处需要传入云函数的event和context，必传
		event,
		context
	})
	const req = JSON.parse(event.body)
	console.log('req', req)
	const userRes = await dbJQL.collection('uni-id-users').doc(req.user_id).field('wx_openid').get()
	console.log("users", userRes)
	if (userRes.code !== 0) return userRes
	if (userRes.data.length === 0) return {
		errCode: 1,
		errMsg: '未找到用户'
	}
	let openid = userRes.data[0].wx_openid.mp
	if (!openid) return {
		errCode: 2,
		errMsg: '用户未关注'
	}
	console.log("openid:", openid)
	let uniSubscribemsg = new UniSubscribemsg({
		dcloudAppid: "__UNI__41D17DD",
		provider: "weixin-mp",
	});
	let data = getNotifyData(req)
	let res = await uniSubscribemsg.sendSubscribeMessage({
		touser: openid,
		template_id: templateids[req.index],
		page: "/uni_modules/zgj-pages/pages/orders/odetail?id=" + req.id, // 小程序页面地址
		miniprogram_state: "formal", // 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
		lang: "zh_CN",
		data: data
	});
	//返回数据给客户端
	return res
};